package com.northpool.operator.common.id;

import cn.hutool.core.io.FileUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.annotation.OutputParam;
import com.northpool.operator.annotation.OutputParams;
import com.northpool.operator.common.algorithm.OperatorTestBuild;
import com.northpool.operator.common.algorithm.TestParamBuilder;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.type.TypeEnum;
import com.northpool.operator.utils.StpOperatorHelper;

import java.io.BufferedInputStream;

@OperatorInfo(
        ref = "FileSha1VerifyOperator",
        version = "sha1",
        name = "文件摘要校验",
        description = "计算文件sha1值并和预期值校验"
)
@OutputParams({
        @OutputParam(ref = "sha1", name = "md5值", desc = "文件实际的md5值"),
        @OutputParam(ref = "result", name = "验证结果", desc = "预期md5和文件实际md5的比对结果"),
})
public class FileSha1VerifyOperator extends StpOperatorHelper {

    @InputParams({
            @InputParam(ref = "file", name = "文件", desc = "文件路径", type = TypeEnum.STRING, required = true),
            @InputParam(ref = "sha1", name = "sha1", desc = "期望sha1，如: d642affbd0af26acdbf5b971cc3d357c", type = TypeEnum.STRING, required = true)
    })
    public FileSha1VerifyOperator() {
    }

    public static void main(String[] args) {
        OperatorTestBuild.execute(FileSha1VerifyOperator.class, TestParamBuilder.aBuilder()
                .param("file", "D:\\uTools-密码管理器-1728727111424.txt")
                .param("sha1", "71390be6cae939327102f2771151dbeca7e3e431")
                .build());
    }

    @Override
    public void execute(ParamTool paramTool) throws Exception {
        String filePath = paramTool.getStr("file");
        String expected = paramTool.getStr("sha1");
        boolean exist = FileUtil.exist(filePath);
        if (!exist) {
            this.error("文件不存在: {}", filePath);
            this.failedExit();
        }

        Digester digester = new Digester(DigestAlgorithm.SHA1);
        // 摘要
        BufferedInputStream inputStream = FileUtil.getInputStream(filePath);
        String digestHex = digester.digestHex(inputStream);
        this.result("sha1", digestHex);
        this.result("result", expected.equals(digestHex));
    }
}
